package name.marz.to.go.ahg.core.responsehandler;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import name.marz.to.go.ahg.common.util.LogUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;


public class DocumentResponseHandler implements ResponseHandler<Document> {
	private String charset = "UTF-8";
	private static final Logger log = Logger.getLogger(DocumentResponseHandler.class.getName());
	
	public DocumentResponseHandler() {
	}
	public DocumentResponseHandler(String charset) {
		this.charset = charset;
	}
	
	@Override
	public Document handleResponse(HttpResponse response)
			throws ClientProtocolException, IOException {
		log.info(response.getStatusLine().toString());
		HttpEntity entity = response.getEntity();
		Document doc = Jsoup.parse(EntityUtils.toString(entity,charset));
		LogUtil.log(Level.FINE, response.getAllHeaders(),"response header");
		LogUtil.logForms(Level.FINE,doc.getAllElements().forms());
		log.finer("doc="+doc.html());
		EntityUtils.consume(entity);
		return doc;
	}
	public String getCharset() {
		return charset;
	}
	public void setCharset(String charset) {
		this.charset = charset;
	}
}
